﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

public class LuaBuilder
{
    static string LuaBuilderPath = string.Format("{0}/../Tools/lua/builder.py", Application.dataPath);

    public static void Build()
    {
        string luaPath = string.Format("{0}/{1}/", Application.dataPath, Config.LUA_PATH);
        string tmpPath = string.Format("{0}/{1}", Application.dataPath, EditorConfig.TEMP_LUA_PATH);
        Build(luaPath, tmpPath);
    }

    public static void Build(string pathSrc, string pathDst, bool patch = false)
    {
        BuildLua(pathSrc, pathDst, LuaArchType.BIT_32, patch);  // 32bit
#if UNITY_IOS
		BuildLua (pathSrc, pathDst, LuaArchType.BIT_64, patch);	// 64bit
#endif
        AssetDatabase.Refresh();
    }

    static void BuildLua(string pathSrc, string pathDst, LuaArchType arch, bool patch)
    {
        if (!Config.LUA_DATA)
        {
            pathDst = FileHelper.ConvertArchName(arch, pathDst);
        }

        if (patch)
        {
            FileHelper.DeleteDirectory(pathDst);
        }

        string pathObj = string.Format("{0}/{1}", pathDst, Config.LUA_PACKAGE);
        FileHelper.CreateDirectory(pathObj);

#if UNITY_STANDALONE
		arch = LuaArchType.NONE;
#else
        if (!ConfigHelper.UseLuaJit)
        {
            arch = LuaArchType.NONE;
        }
#endif
        arch = LuaArchType.NONE;
        string command = @"D:\Python2.7\python.exe";
        string args = string.Format("{0} {1} {2} {3}", LuaBuilderPath, pathSrc, pathObj, (int)arch);
        Debug.Log("args:"+args);

        // 调用外部Shell编译
        ShellHelper.ProcessCommandEx(command, args);

        if (Config.LUA_DATA)
        {
            // 打包
            pathDst = FileHelper.ConvertArchName(arch, pathDst);

            FileHelper.DeleteDirectory(pathDst);
            FileHelper.CreateDirectory(pathDst);
            PackLuaAsset(pathObj, string.Format("{0}/{1}.asset", pathDst, Config.LUA_PACKAGE), "bytes");

            // 移除编译中间文件
            FileHelper.DeleteDirectory(pathObj);
        }
    }

    static void PackLuaAsset(string path, string file, string ext = "lua")
    {
        if (!path.EndsWith("/"))
        {
            path += "/";
        }
        LuaData data = ScriptableObject.CreateInstance<LuaData>();
        data.encode = EditorConfig.LUA_PACKAGE_ENCODE;
        data.files = new List<LuaData.FileInfo>();

        List<string> files = FileHelper.GetAllChildFiles(path, ext);
        string dotExt = string.Format(".{0}", ext);

        string crypName = "", outName = "";
        for (int i = 0; i < files.Count; ++i)
        {
            string filePath = files[i];
            crypName = filePath.Replace(path, "").Replace(dotExt, "").Replace("\\", "_").Replace("/", "_");

            byte[] bytes = System.IO.File.ReadAllBytes(filePath);

            switch (data.encode)
            {
                case LuaData.EncodeType.Base64:
                    string content = System.Convert.ToBase64String(bytes);
                    bytes = System.Text.Encoding.Default.GetBytes(content);
                    break;
            }

            LuaData.FileInfo info = new LuaData.FileInfo();
            info.name = crypName;
            info.bytes = bytes;

            data.files.Add(info);
        }

        file = "Assets" + file.Replace(Application.dataPath, "");
        AssetDatabase.CreateAsset(data, file);
    }
}